package com.leyou.user.web;

import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.local.UserContext;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("info")
public class UserInfoController {

    @Autowired
    private UserService userService;

    /**
     * 校验数据是否存在
     *
     * @param data 要校验的数据
     * @param type 数据的类型，1：用户名，2：手机号
     * @return 是否存在，true存在，false不存在
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> checkDataExists(
            @PathVariable("data") String data, @PathVariable("type") Integer type) {
        return ResponseEntity.ok(userService.checkDataExists(data, type));
    }

    /**
     * 发送短信验证码
     *
     * @param phone 手机号
     * @return 无
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone) {
        userService.sendCode(phone);
        // 返回204，无响应结果
        return ResponseEntity.noContent().build();
    }

    /**
     * 用户注册
     *
     * @param user 用户信息
     * @param code 验证码
     * @return 无
     */
    @PostMapping
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code) {
        // 判断校验的结果
        if(result.hasErrors()){
            String msg = result.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage).collect(Collectors.joining("|"));
            // 有错误
            throw new LyException(400, "请求参数有误," + msg);
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据用户名和密码查询用户
     * @param username 用户名
     * @param password 密码
     * @return 用户
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ) {
        return ResponseEntity.ok(userService.queryByUsernameAndPassword(username, password));
    }

    @GetMapping("me")
    public ResponseEntity<UserDetails> whoAmI(){
        // 从上下文中获取用户，并返回
        return ResponseEntity.ok(UserContext.getUser());
    }
}
